package cn.itcast.nems.job;

import cn.itcast.nems.approval.dao.entity.ApprovalForm;
import cn.itcast.nems.approval.service.ApprovalFormService;
import cn.itcast.nems.common.account.AccountHolder;
import cn.itcast.nems.common.account.AccountInfo;
import cn.itcast.nems.common.tenant.TenantInfo;
import cn.itcast.nems.common.tenant.TenantInfoHolder;
import cn.itcast.nems.journal.service.JournalTransferService;
import cn.itcast.nems.manager.msas.MsasManager;
import cn.itcast.nems.manager.support.ApprovalMessageHolder;
import cn.itcast.nems.manager.support.ApprovalMessageInfo;
import com.itcast.msas.sdk.acm.domain.AccountDto;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Slf4j
@Component
@RequiredArgsConstructor
public class ManualSyncJob {

    private final JournalTransferService transferService;
    private final ApprovalFormService approvalFormService;
    private final MsasManager msasManager;
    @Value("${spring.profiles.active}")
    private String ACTIVE;

    @XxlJob("manualSyncJournal")
    public ReturnT<String> manualSyncJournal(String formID) {
        try {
            formID = formID.trim();
            log.info("手动触发凭单同步老EMS数据，formID: {}", formID);
            TenantInfoHolder.setTenantInfo(TenantInfo.DEFAULT_TENANT_INFO);
            ApprovalForm approvalForm = approvalFormService.getById(formID);
            Assert.notNull(approvalForm, "未找到对应的凭单信息 : " + formID);
            setAccount(approvalForm);
            ApprovalMessageHolder.set(new ApprovalMessageInfo(
                    approvalForm.getJournalId(),
                    approvalForm.getJournalId(),
                    approvalForm.getJournalType(),
                    approvalForm.getBpmBizKey(),
                    ACTIVE,
                    "XXL-JOB: " + System.currentTimeMillis()
            ));
            transferService.manualSync(approvalForm);
            return new ReturnT<>("OK");
        } finally {
            ApprovalMessageHolder.clear();
            TenantInfoHolder.clear();
            AccountHolder.clear();
        }
    }

    private void setAccount(ApprovalForm approvalForm) {
        final String email = approvalForm.getCreatedBy();
        final AccountDto account = this.msasManager.getAccount(email);
        final AccountInfo accountInfo = new AccountInfo(email,
                account.getName(),
                account.getEmployeeNumber(),
                "");
        AccountHolder.setAccountInfo(accountInfo);
    }

}
